package com.example.servletdemo.mvc.controller;

import com.example.servletdemo.model.Result;
import com.example.servletdemo.model.User;
import com.example.servletdemo.mvc.model.Student;
import com.example.servletdemo.mvc.model.TResult;
import com.example.servletdemo.mvc.service.inter.StudentServiceInter;
import com.example.servletdemo.mvc.service.inter.UserServiceInter;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;

/**
 * 用户相关  结合modelAndView
 */
@Controller
public class UserController {
    @Resource
    StudentServiceInter studentServiceInter;

    @Resource
    UserServiceInter userServiceInter;

    @GetMapping("/regist")
    public ModelAndView regist(){
        ModelAndView view = new ModelAndView("regist");
        Student student = new Student();
        student.setName("哈喽");
        student.setAge(12);
        //传输数据
        view.addObject("name",student.getName());
        view.addObject("student",student);
        return view;
    }

    @GetMapping("/login")
    public ModelAndView login(){
        ModelAndView view = new ModelAndView("login");
        return view;
    }

    /**
     * 用户登录
     * @param user
     * @return
     */
    @PostMapping("/login")
    @ResponseBody
    public TResult login(@RequestBody User user){
        return userServiceInter.login(user);
    }

    /**
     * 用户登录执行接口
     * @param username
     * @param password
     * @return
     */
    @RequestMapping(value = "/userLogin", method = RequestMethod.POST)
    public ModelAndView userLogin(@RequestParam("username") String username,
                                  @RequestParam("password") String password){
        ModelAndView view = new ModelAndView("loginTip");
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        TResult result = userServiceInter.login(user);
        boolean success = result.isSuccess();
        if(success){
            view.addObject("msg","登录成功");
        }else {
            view.addObject("msg","登录失败,"+result.getErrMsg());
        }
        return  view;
    }


    /**
     * 获取用户信息
     * @return
     */
    @GetMapping("/getUserInfo")
    @ResponseBody
    public Result getStudentInfo(int id){
        if(id<10){
            Result result = new Result();
            result.setSuccess(false);
            result.setErrorCode(-1);
            return result;
        }
        return studentServiceInter.getStudentInfo(id);
    }
}
